<template>
  <div>
    <el-dialog title="工艺工序" :visible.sync="showDialog" top="0" width="90%" :close-on-click-modal="false" @close="close()">
      <div class="top-header">
        <div class="left">
          <el-button type="primary" @click="showDialogInner = true">添加</el-button>
          <el-button :disabled="!delActive" type="danger" @click="del()">删除</el-button>
        </div>
        <div class="right">
          <el-button type="primary" @click="showDialogSOP = true">产品工艺总SOP</el-button>
          <span v-if="selectedItem && selectedItem.fileId" style="margin-left: 10px;color:#67c23a;">已上传</span>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table v-loading="tableLoading" :data="tableData" stripe border height="300px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="processesName" label="工序名称" />
          <el-table-column prop="number" label="步骤号" />
          <el-table-column prop="fileId" label="是否上传SOP">
            <template v-if="!('index' in scope.row)" slot-scope="scope">
              {{ scope.row.fileId ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column width="250" label="操作">
            <template v-if="!('index' in scope.row)" slot-scope="scope">
              <el-button type="text" class="text-btn-cursor" size="small" @click="edit(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination :light="true" :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="savebtn" @click="cancel()">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="titleText" :visible.sync="showDialogInner" width="35%" top="0" :close-on-click-modal="false" @close="cancelInner()">
      <el-form ref="form" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="工序名称：" prop="processesName" class="w100p">
          <el-input v-model="formData.processesName" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="步骤序号：" prop="number" class="w100p">
          <el-input-number :precision="0" v-model="formData.number" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="SOP文件：" prop="fileId" class="w100p">
          <UploadFile :file-list.sync="fileList" module-type="PROCESSTEST" @addFile="upload" @removeFile="remove">
            <el-button size="small" type="primary">点击上传</el-button>
          </UploadFile>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancelInner()">取 消</el-button>
        <el-button :loading="saveLoadingInner" type="primary" class="savebtn" @click="saveInner()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="产品总工艺SOP" :visible.sync="showDialogSOP" width="35%" top="0" :close-on-click-modal="false" @close="cancelSOP()">
      <el-form ref="form" label-position="left" :model="formDataSOP" class="el-form">
        <el-form-item label="总工艺SOP：" prop="fileId" class="w100p">
          <UploadFile :file-list.sync="fileListSOP" module-type="PROCESSTEST" @addFile="uploadSOP" @removeFile="removeSOP">
            <el-button size="small" type="primary">点击上传</el-button>
          </UploadFile>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancelSOP()">取 消</el-button>
        <el-button :loading="saveLoadingSOP" type="primary" class="savebtn" @click="saveSOP()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/processing-management/basic-info-manage/product-process';
import UploadFile from '@/components/UploadFile/index';
import Pagination from '@/components/Pagination';
import CommonFileApi from '@/api/common-file';
export default {
  components: { UploadFile, Pagination },
  props: {
    value: Boolean,
    selectedItem: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      formData: {
        processesName: '',
        number: 1,
        fileId: '',
        fileName: ''
      },
      formDataSOP: {
        fileId: '',
        fileName: ''
      },
      saveLoading: false,
      saveLoadingInner: false,
      showDialog: false,
      selectedItemInner: null,
      showDialogInner: false,
      fileList: [],
      rules: {
        processesName: [
          {
            required: true,
            message: '请输入工序名称'
          }
        ]
      },
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      tableData: [],
      fileListSOP: [],
      showDialogSOP: false,
      saveLoadingSOP: false,
      delActive: false,
      selectedList: [],
      moduleType: 'PROCESSTEST',
      upDownType: 'FTP'
    };
  },
  computed: {
    titleText() {
      return this.selectedItemInner ? '编辑工序' : '新增工序';
    }
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (v) {
        this.init();
      }
    }
  },
  created() {
    this.showDialog = this.value;
  },
  mounted() {},
  methods: {
    reset() {
      this.$refs.form.resetFields();
      this.formData = {
        processesName: '',
        number: 1,
        fileId: ''
      };
      this.fileList = [];
      this.selectedItemInner = null;
    },
    init() {
      const { selectedItem, upDownType, moduleType } = this;
      this.formDataSOP.fileId = selectedItem.fileId;
      this.formDataSOP.fileName = selectedItem.fileName;
      if (this.formDataSOP.fileId) {
        this.fileListSOP = [
          {
            fileId: selectedItem.fileId,
            name: selectedItem.fileName,
            url: CommonFileApi.getFileUrl({
              upDownType,
              moduleType,
              fileId: selectedItem.fileId
            })
          }
        ];
      }
      this.currentPage = 1;
      this.getList();
    },
    saveInner() {
      const { formData, selectedItem, selectedItemInner } = this;
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.saveLoadingInner = true;
          if (selectedItemInner) {
            api
              .editProcesses({ productId: selectedItem.productId, processesId: selectedItemInner.processesId, ...formData })
              .then(res => {
                if (res.code === 1) {
                  this.getList();
                  this.$message.success(res.msg);
                  this.cancelInner();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoadingInner = false;
              });
          } else {
            api
              .addProcesses({ productId: selectedItem.productId, ...formData })
              .then(res => {
                if (res.code === 1) {
                  this.getList();
                  this.$message.success(res.msg);
                  this.cancelInner();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoadingInner = false;
              });
          }
        }
      });
    },
    saveSOP() {
      const { selectedItem, formDataSOP } = this;
      this.saveLoadingSOP = true;
      api
        .editProduct({
          ...selectedItem,
          fileId: formDataSOP.fileId,
          fileName: formDataSOP.fileName,
          productId: selectedItem.productId
        })
        .then(res => {
          if (res.code === 1) {
            this.$emit('reflash');
            this.$emit('updateSelectedItem', res.data);
            this.$message.success('保存成功');
            this.showDialogSOP = false;
          }
        })
        .finally(_ => {
          this.saveLoadingSOP = false;
        });
    },
    close() {
      this.$emit('reflash');
      this.$emit('input', false);
    },
    cancel() {
      this.$emit('input', false);
    },
    cancelInner() {
      this.showDialogInner = false;
      setTimeout(() => {
        this.reset();
      }, 250);
    },
    cancelSOP() {
      this.showDialogSOP = false;
    },
    upload(data, file) {
      this.formData.fileId = data.data.fileId;
      this.formData.fileName = file.name;
      this.$refs.form.clearValidate();
    },
    remove() {
      this.formData.fileId = '';
      this.formData.fileName = '';
    },
    uploadSOP(data, file) {
      this.formDataSOP.fileId = data.data.fileId;
      this.formDataSOP.fileName = file.name;
    },
    removeSOP() {
      this.formDataSOP.fileId = '';
      this.formDataSOP.fileName = '';
    },
    getList() {
      const { currentPage, pageSize, selectedItem } = this;
      this.tableLoading = true;
      api
        .getProcessesList({
          page: currentPage,
          size: pageSize,
          entity: {
            productId: selectedItem.productId
          }
        })
        .then(res => {
          if (res.code === 1) {
            this.tableData = this.$utils.addblankmet(res.data.content, pageSize);
            this.totalSize = res.data.totalElements;
            if (res.data.content.length === 0 && this.currentPage !== 1) {
              this.currentPage--;
              this.getList();
            }
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    edit(item) {
      const { upDownType, moduleType } = this;
      this.selectedItemInner = JSON.parse(JSON.stringify(item));
      for (let key in this.formData) {
        this.formData[key] = item[key];
      }
      if (item.fileId) {
        this.fileList = [
          {
            fileId: item.fileId,
            name: item.fileName,
            url: CommonFileApi.getFileUrl({
              upDownType,
              moduleType,
              fileId: item.fileId
            })
          }
        ];
      }
      this.showDialogInner = true;
    },
    handleSelectionChange(list) {
      this.selectedList = list.map(item => {
        return item.processesId;
      });
      if (this.selectedList && this.selectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getList();
    },
    del() {
      this.handleDelete(this.selectedList);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no;
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.delProcesses({ processesIdList: list }).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功');
              this.getList();
              this.$emit('reflash');
            }
          });
        })
        .catch(_ => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.top-header {
  width: 100%;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .left {
    flex: 1;
  }
}
.table-wrapper {
  position: relative;
  padding-bottom: 50px;
  box-sizing: border-box;
}
</style>
